<?php
/**
* albums Class
*/

class albums
extends entity
{
	/**
	* Optional Constructor: Load on demand only.
	*/
	public function __construct()
	{
		# Parent's default constructor is necessary.
		parent::__construct();

		/**
		* Set Private, Protected or Public Members
		*/
		$this->protection_code = 'effb1a77e9a80b0d8e3a04488d46091c'; # Some random text, valid for the entire life
		$this->table_name = 'gallery_albums'; # Name of this table/entity name
		$this->pk_column = 'album_id'; # Primary Key's Column Name

		/**
		* Validation fields as used in add/edit forms
		*/
		$this->fields = array(
			# Remove the columns that you do not want to use in the ADD form
			'add' => array(
				'album_name' => null,
				'album_folder' => null,
				'album_folder_local' => null,
				'album_coverimage' => null,
				'album_description' => null,
			),
			
			# Remove the columns that you do not want to use in the EDIT form
			'edit' => array(
				'album_name' => null,
				'album_folder' => null,
				'album_folder_local' => null,
				'album_coverimage' => null,
				'album_description' => null,
			),
		);
	}

	/**
	* List entries from [ albums ]
	* Column `code` signifies a protection code while deleting/editing a record
	* @param $conditions SQL Conditions
	* @return Multi-Dimensional array of entries in the list
	*/
	public function list_entries(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ albums ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`album_id`, # Do not remove this
	
	e.is_approved,
	e.is_locked,
	
	e.`album_name`,
	e.`album_folder`,
	e.`album_folder_local`,
	e.`album_coverimage`,
	
	e.`images_counter`,
	
	MD5(CONCAT(`album_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_albums` `e`
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# We assume that the sorting fields are available
	#`sink_weight` ASC,
	#album_name,
	`album_id` DESC
LIMIT {$from_index}, {$per_page}
;";
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	/**
	* Details of an entity in [ albums ] for management activities only.
	* @param $pk integer Primary Key's value of an entity
	* @return $details Associative Array of Detailed records of an entity
	*/
	public function details($album_id=0)
	{
		global $subdomain_id;
		$album_id = (int)$album_id;
		$details_sql="
SELECT
	e.`album_id`, # Do not remove this

	e.*, # Modify these columns,
	
	# Admin must have it to EDIT the records
	MD5(CONCAT(`album_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_albums` `e`
WHERE
	`album_id` = {$album_id}
	# AND subdomain_id={$subdomain_id}
;";
		$details = $this->row($details_sql);
		return $details;
	}

	/**
	* Details of an entity in [ albums ] for public display.
	* @param $pk integer Primary Key's value of an entity
	* @return $details Associative Array of Detailed records of an entity
	*/
	public function get_details($album_id=0, $protection_code='')
	{
		$protection_code = $this->sanitize($protection_code);
		$album_id = (int)$album_id;
		$details_sql="
SELECT
	`album_id`, # Do not remove this

	e.*, # Modify these columns

	MD5(CONCAT(`album_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_albums` `e`
WHERE
	`album_id` = {$album_id}
	AND e.is_active='Y'

	# Optionally validate
	AND MD5(CONCAT(`album_id`, '{$this->protection_code}')) = '{$protection_code}'
;";
		$details = $this->row($details_sql);
		return $details;
	}

	/**
	* Flag a field; dummy use; unless you use it.
	* Every method should sanitize the user input.
	* It will co-exist with the live features.
	*/
	public function flag_field($album_id=0, $protection_code='', $field_name='')
	{
		$album_id = (int)$album_id;
		$protection_code = $this->sanitize($protection_code);
		$subdomain_id = framework::subdomain_id();
		
		# Selected fields allowed to flag Y/N
		if(!in_array($field_name, array('is_approved', 'approve_all', 'is_featured', 'is_locked')))
			return false;
		
		if($field_name=='approve_all')
		{
			$approve_all_images_sql="UPDATE `gallery_images_albums` SET is_approved='Y' WHERE album_id={$album_id};";
			$this->query($approve_all_images_sql);
			
			# Approves all parent images that contain the data
			$approve_all_images_sql="UPDATE `gallery_images` SET is_approved='Y' WHERE image_id IN (SELECT image_id FROM gallery_images_albums WHERE album_id={$album_id});";
			$this->query($approve_all_images_sql);
			
			return true;
		}
		
		if($field_name=='is_locked')
		{
			# Verfy special case - link arrived from clicking on the LOCK icon to invert all locks
			# invert the entire locks
			if(isset($_GET['invert']) && $_GET['invert']=='true')
			{
				$invert_all_locks_sql="UPDATE `gallery_albums` SET is_locked=IF(is_locked='Y', 'N', 'Y');";
				return $this->query($invert_all_locks_sql);
			}
		}

		$flag_sql="
UPDATE `gallery_albums` SET
	# Set your flag name here
	`{$field_name}`=IF(`{$field_name}`='Y', 'N', 'Y')
WHERE
	`album_id` = {$album_id}
	AND subdomain_id={$subdomain_id}
	
	# Don't touch the deleted flags
	AND is_active='Y'

	# Optionally validate
	AND MD5(CONCAT(`album_id`, '{$this->protection_code}')) = '{$protection_code}'
;";
		return $this->query($flag_sql);
	}

	/**
	* Welcome and ask for authentication?
	* Please extend this method according to your business logic.
	* Used right after a new albums is added.
	*/
	public function welcome_first($album_id=0)
	{
		$album_id = (int)$album_id;
	 	
		return true;
	}
	
	
	
	/**
	* Scan album folder for images
	*/
	public function scan_folder($album_id=0, $protection_code='')
	{
		$album_id = (int)$album_id;
		$protection_code = $this->sanitize($protection_code);
		
		$album_folder = $this->folder_path($album_id, $protection_code);
		
		if(!$album_folder) return false;
		if(!is_dir($album_folder)) die('Folder des not exist for this album. Please correct it first.');
		
		$album = new scanner_manual($album_folder, $album_id);
	}
	
	/**
	* Find out folder path of an album
	*/
	public function folder_path($album_id=0, $protection_code='')
	{
		$album_id = (int)$album_id;
		$protection_code = $this->sanitize($protection_code);
		$folder_sql="SELECT album_folder FROM gallery_albums WHERE album_id={$album_id};";
		$folder = $this->row($folder_sql);
		if(!isset($folder['album_folder']))
		{
			$folder = array('album_folder' => '/tmp');
			die("Album folder not available");
		}
		else if(!is_dir($folder['album_folder']) || !is_writable($folder['album_folder']))
		{
			$folder['album_folder'] = '/tmp';
			die("Cannot write to: {$folder['album_folder']}");
		}
		return $folder['album_folder'];
	}
	
	/**
	* Fixes the number of images counter under an album
	*/
	public function fix_counter($album_id=0, $protection_code='')
	{
		$album_id = (int)$album_id;
		$protection_code = $this->sanitize($protection_code);
		$counter = $this->row("SELECT COUNT(*) total FROM gallery_images_albums WHERE album_id={$album_id} AND is_active='Y' AND is_approved='Y';");
		
		$update_images_counter_sql = "UPDATE gallery_albums SET images_counter={$counter['total']} WHERE album_id={$album_id};";
		$this->query($update_images_counter_sql);
		
		return true;
	}
	
	/**
	* Finds out all store locations that should be used
	*/
	public function get_store_locations($album_id=0, $protection_code='')
	{
		$album_id = (int)$album_id;
		$protection_code = $this->sanitize($protection_code);
		
		$store_locations_sql="
SELECT
	`as`.album_id,
	s.size_id,
	s.size_name,
	s.size_code,
	`as`.store_location
FROM gallery_albums_sizes `as`
RIGHT OUTER JOIN gallery_sizes s
	ON `as`.size_id=s.size_id
	AND `as`.album_id={$album_id}
WHERE
	`s`.is_active='Y' AND `s`.is_approved='Y'
	# `as`.is_active='Y' AND `as`.is_approved='Y'
ORDER BY
	#s.sink_weight,
	s.dimension_width,
	s.dimension_height
;";
		#die($store_locations_sql);
		$locations = $this->arrays($store_locations_sql);
		return $locations;
	}
}
?>